/**     
 * @Title: SessionIdFilter.java   
 * @Package com.yitong.spring.filter
 * @Description: TODO
 * @author weiwei 
 * @date 2017年7月21日 下午6:00:57   
 * @version V1.0     
 */
package com.yitong.spring.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * @ClassName: SessionIdFilter
 * @Description: TODO
 * @author weiwei
 * @date 2017年7月21日 下午6:00:57
 * 
 */
public class SessionIdFilter extends OncePerRequestFilter {

	private static String SESSION_ID_KEY = "sid";

	private static String SESSION_ID_HEADER = "X-SESSION-ID";

	@Override
	protected void doFilterInternal(ServletRequest req, ServletResponse rsp, FilterChain chain) throws ServletException, IOException {
		String sid = WebUtils.getCleanParam(req, SESSION_ID_KEY);
		if (StringUtils.isBlank(sid)) {
			Session session = SecurityUtils.getSubject().getSession(true);
			String sessionId = session.getId().toString();
			HttpServletResponse httpRsp = WebUtils.toHttp(rsp);
			httpRsp.addHeader(SESSION_ID_HEADER, sessionId);
		} else {
			Session session = SecurityUtils.getSubject().getSession(false);
			// 会话不存在时，则创建新会话，并将sid写到响应头
			if (session == null) {
				session = SecurityUtils.getSubject().getSession(true);
				String sessionId = session.getId().toString();
				HttpServletResponse httpRsp = WebUtils.toHttp(rsp);
				httpRsp.addHeader(SESSION_ID_HEADER, sessionId);
			} // 会话存在，但sid与服务端的会话id不一致时，并将sid写到响应头
			else {
				String sessionId = session.getId().toString();
				if (!sid.equals(sessionId)) {
					HttpServletResponse httpRsp = WebUtils.toHttp(rsp);
					httpRsp.addHeader(SESSION_ID_HEADER, sessionId);
				}
			}
		}
		chain.doFilter(req, rsp);
	}
}
